package com.com.gmail.at.vssabinin.adminclient;

import java.util.HashSet;
import java.util.List;

import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;

import DTO.TrainDTO;

public class TrainManager extends javax.swing.JDialog {

	private static final long serialVersionUID = 1L;

    public TrainManager(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        setResizable(false);
        initComponents();
    }
    
    private HashSet<TrainDTO> createdTrains = new HashSet<TrainDTO>();
    private HashSet<TrainDTO> removedTrains = new HashSet<TrainDTO>();
    
    private boolean changes = false;
   
    private void initComponents() {

        scrollArea = new javax.swing.JScrollPane();
        trainList = new javax.swing.JList();
        deleteTrain = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        addTrain = new javax.swing.JButton();
        save = new javax.swing.JButton();
        trainNumber = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        goBack = new javax.swing.JButton();
        loadAll = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        trainPlaces = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        trainList.setModel(new javax.swing.AbstractListModel() {
			private static final long serialVersionUID = 1L;
			String[] strings = { "Trains" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        scrollArea.setViewportView(trainList);

        deleteTrain.setText("delete");
        deleteTrain.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                deleteTrainMouseReleased(evt);
            }
        });

        jLabel1.setText("Choose a train and press delete:");

        addTrain.setText("add train");
        addTrain.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                addTrainMouseReleased(evt);
            }
        });

        save.setText("save changes");
        save.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                saveMouseReleased(evt);
            }
        });

        trainNumber.setText("train number");

        jLabel2.setText("Add a new train:");

        goBack.setText("go back to the main menu");
        goBack.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                goBackMouseReleased(evt);
            }
        });

        loadAll.setText(" Refresh the list");
        loadAll.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                loadAllMouseReleased(evt);
            }
        });
      

        jLabel3.setText("First you add or delete trains. After you press save changes.");

        trainPlaces.setText("places");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        layout.setAutoCreateGaps(true);
        layout.setAutoCreateContainerGaps(true);
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(jLabel3)
                        .addGap(0, 27, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(goBack)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(save))
                    .addComponent(scrollArea)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(24, 24, 24)
                        .addComponent(deleteTrain, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(trainNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(trainPlaces)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(addTrain, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(117, 117, 117)
                .addComponent(loadAll)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addComponent(loadAll)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(scrollArea, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(deleteTrain))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(trainNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(addTrain)
                    .addComponent(trainPlaces, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(goBack)
                    .addComponent(save))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 38, Short.MAX_VALUE)
                .addContainerGap())
        );

       
        pack();
    }
    public static TrainManager trainInstance = new TrainManager(Main.mainInstance, true);
    
    private  DefaultListModel listModel = new DefaultListModel();
    
    private void update() {
    	listModel.clear();
    	Main.mainInstance.client.sendThroughProtocol("adminManageTrainDat", "");
        Protocol.Message message = Main.mainInstance.client.readThroughProtocol();
        if (message.getType().equals("ok")) {
        	@SuppressWarnings("unchecked")
        	List<TrainDTO> train = (List<TrainDTO>)message.getObject();
            for (int i = 0; i < train.size(); i++) {
            	this.listModel.addElement("Train number:  " + train.get(i).getTrainNumber() + 
              			"   places:  " + train.get(i).getPlaces());
            }
        } else if (message.getType().equals("no")) {
        	listModel.addElement("No trains in database");
        }
        TrainManager.trainInstance.trainList.setModel(listModel);
    }
    
    private void loadAllMouseReleased(java.awt.event.MouseEvent evt) {
    	this.update();
    }

    private void addTrainMouseReleased(java.awt.event.MouseEvent evt) {
    	TrainDTO train = new TrainDTO();
    	try {
    		train.setPlaces(Integer.valueOf(this.trainPlaces.getText()));
    		train.setTrainNumber(Integer.valueOf(this.trainNumber.getText()));
    		this.createdTrains.add(train);
        	this.listModel.addElement("Train number:  " + train.getTrainNumber() + 
          			"   places:  " + train.getPlaces());
        	TrainManager.trainInstance.trainList.setModel(listModel);
        	this.changes = true;
    	} catch (NumberFormatException e) {
    		JOptionPane.showMessageDialog(null, "Incorrect number format of places or train number!"); 
    	}
    }

    private void saveMouseReleased(java.awt.event.MouseEvent evt) {
        if (!this.createdTrains.isEmpty()) {
        	Main.mainInstance.client.sendThroughProtocol("adminCreateNewTrains", this.createdTrains);
        	Protocol.Message message = Main.mainInstance.client.readThroughProtocol();
        	if (message.getType().equals("ok")) {
        		this.createdTrains.clear();	
        	}
        }
        if (!this.removedTrains.isEmpty()) {
        	Main.mainInstance.client.sendThroughProtocol("adminRemoveTrains", this.removedTrains);
        	Protocol.Message message1 = Main.mainInstance.client.readThroughProtocol();
        	if (message1.getType().equals("ok")) {
        		this.removedTrains.clear();
        	}
		}
        this.update();
        this.changes = false;
        JOptionPane.showMessageDialog(null, "You have successfully made ​​changes!"); 
    }

    private void deleteTrainMouseReleased(java.awt.event.MouseEvent evt) {
    	int selection = JOptionPane.showConfirmDialog(null, "This will delete the train, and all the schedules and tickets, that are associated with it!", "Warning", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
    	if (selection == JOptionPane.YES_OPTION) {
            String selected = (String) this.trainList.getSelectedValue();
            this.listModel.remove(this.trainList.getSelectedIndex());
            TrainManager.trainInstance.trainList.setModel(listModel); 
            String trainNumber = selected.replace("Train number:  ", "").replaceAll("   places:.+", "");
            TrainDTO train = new TrainDTO();
        	train.setTrainNumber(Integer.valueOf(trainNumber));
        	this.removedTrains.add(train);
        	changes = true;
    	}
    }

    private void formWindowOpened(java.awt.event.WindowEvent evt) {
        this.update();
    }

    private void goBackMouseReleased(java.awt.event.MouseEvent evt) {
    	if (changes) {
    		int selection = JOptionPane.showConfirmDialog(null, "Do you want to save changes?", "Information", 
        			JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE);
        	if (selection == JOptionPane.YES_OPTION) {
        		this.saveMouseReleased(evt);
        	}
    	}
    	Main.mainInstance.loginViewSet();
        this.dispose();
    }

    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TrainManager.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TrainManager.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TrainManager.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TrainManager.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
     
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                TrainManager dialog = new TrainManager(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
           }
        });
    }
    private javax.swing.JButton addTrain;
    private javax.swing.JButton deleteTrain;
    private javax.swing.JButton goBack;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane scrollArea;
    private javax.swing.JButton loadAll;
    private javax.swing.JButton save;
    private javax.swing.JList trainList;
    private javax.swing.JTextField trainNumber;
    private javax.swing.JTextField trainPlaces;
}
